package hkust.lingx.csit5110.android.lib.server;

import hkust.lingx.csit5110.android.lib.model.AnchorMessage;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.ArrayList;

import android.os.Handler;
import android.os.Message;

/**
 * when receive a client socket connection,server will create an instance of 
 * ServerhandlerThread to do the work which is call all the  Handler
 * @author lingx825
 *
 */
 public class ServerHandlerThread implements Runnable {
  private Socket socket;
  private ObjectInputStream oos;
  private NumbServer server;

  public ServerHandlerThread(NumbServer numbServer, Socket clientSocket) {
    try {
      server = numbServer;
      socket = clientSocket;
      oos = new ObjectInputStream(socket.getInputStream());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void run() {
    try {
      AnchorMessage msg = (AnchorMessage) oos.readObject();
      this.invokeHandler(msg);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void invokeHandler(AnchorMessage msg) {
    ArrayList<Handler> handlerList = server.getHandlerList();
    for (Handler handler : handlerList) {
      Message m=new Message();      
      m.obj=msg;
      handler.sendMessage(m);
    }
  }

}
